package com.adk.backend.controller;

import com.adk.backend.common.Result;
import com.adk.backend.util.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class FileUploadController {
    
    @Autowired
    private FileUploadUtil fileUploadUtil;
    
    /**
     * 上传文件
     */
    @PostMapping("/file")
    public Result<Map<String, String>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "folder", defaultValue = "uploads") String folder) {
        try {
            if (file == null || file.isEmpty()) {
                return Result.error("文件不能为空");
            }
            
            String fileUrl = fileUploadUtil.uploadFile(file, folder);
            
            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("fileName", file.getOriginalFilename());
            
            return Result.success("文件上传成功", result);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }
    
    /**
     * 上传收货照片
     */
    @PostMapping("/receive")
    public Result<Map<String, String>> uploadReceiveImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(required = false) Long olId,
            @RequestParam(required = false) Long uId,
            @RequestParam(required = false) Integer ctnNo) {
        try {
            String folder = "receive/" + (olId != null ? olId : "default");
            String fileUrl = fileUploadUtil.uploadFile(file, folder);
            
            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("fileName", file.getOriginalFilename());
            
            return Result.success("照片上传成功", result);
        } catch (Exception e) {
            log.error("照片上传失败", e);
            return Result.error("照片上传失败：" + e.getMessage());
        }
    }
}


